package com.pactera.madp.cp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pactera.madp.cp.api.dto.track.BehaviorTrackDto;
import com.pactera.madp.cp.api.entity.BehaviorTrackEntity;
import com.pactera.madp.cp.api.entity.WorkContactEmployeeEntity;
import com.pactera.madp.cp.api.entity.clientLossManagement.RemindCommunicationEntity;
import com.pactera.madp.cp.api.entity.clientLossManagement.RemindTaskRecordsEntity;
import com.pactera.madp.cp.common.constant.BehaviorTrackFormatConst;
import com.pactera.madp.cp.mapper.WorkContactEmployeeMapper;
import com.pactera.madp.cp.service.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Slf4j
@Service
@AllArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class BehaviorTrackUntalkServiceImpl extends BaseBehaviorTrackServer {

    @Autowired
    private RemindTaskRecordsService remindTaskRecordsService;

    private RemindCommunicationService remindCommunicationService;

    private final WorkContactEmployeeMapper contactEmployeeMapper;

    @Override
    public void handleEvent(BehaviorTrackDto dto, IWorkEmployeeService workEmployeeService,
                            IWorkContactService workContactService, HttpServletResponse response) throws Exception{

        RemindCommunicationEntity remindCommunicationEntity = remindCommunicationService.list()
                .stream()
                .max(Comparator.comparing(l -> l.getCreateTime()))
                .get();
        log.info("remindCommunicationEntity:{}",remindCommunicationEntity);
        if (remindCommunicationEntity == null) {
            return;
        }
        RemindTaskRecordsEntity remindTaskRecordsEntity = remindTaskRecordsService.getOne(new LambdaQueryWrapper<RemindTaskRecordsEntity>()
                .eq(RemindTaskRecordsEntity::getWxUserId, dto.getWxUserId())
                .eq(RemindTaskRecordsEntity::getWxExternalUserid, dto.getWxExternalUserid())
                .eq(RemindTaskRecordsEntity::getIsFinished,"0"));
        if (remindTaskRecordsEntity == null) {
            return;
        }
        log.info("remindTaskRecordsEntity:{}",remindTaskRecordsEntity);
        remindTaskRecordsEntity.setIsFinished(remindCommunicationEntity.getTimes().equals(remindTaskRecordsEntity.getExecutedTimes()+1) ? "1" : "0");
        remindTaskRecordsEntity.setExecutedTimes(remindTaskRecordsEntity.getExecutedTimes()+1);
        //更新成员未交流提醒定时任务记录表
        remindTaskRecordsService.updateById(remindTaskRecordsEntity);

        //事件处理
        BehaviorTrackEntity entity = new BehaviorTrackEntity();
        BeanUtil.copyProperties(dto, entity);
        baseHandleEvent(entity, workEmployeeService, workContactService, this, response);

    }

    @Override
    protected String buildData(BehaviorTrackEntity entity) {
        List<WorkContactEmployeeEntity> contactEmployeeEntities = contactEmployeeMapper.getLossContact(entity.getCorpId(), entity.getContactId(), entity.getEmployeeId());
        //根据更新时间取该客户与成员关系最新的记录
        WorkContactEmployeeEntity max = contactEmployeeEntities.stream().max(Comparator.comparing(l -> l.getUpdateTime())).get();
        List<String> datas = new ArrayList<>();
        datas.add(entity.getUsername());
        datas.add(entity.getExternalUsername());
        if (!JSONArray.parseArray(max.getRemarkMobiles()).isEmpty()) {
            datas.add(JSONArray.parseArray(max.getRemarkMobiles()).get(0).toString());
        }
        datas.add(entity.getWxUserId());
        datas.add(entity.getWxExternalUserid());
        String content = "";
        if (!JSONArray.parseArray(max.getRemarkMobiles()).isEmpty()) {
            content = String.format(BehaviorTrackFormatConst.UntalkFormFormat1, datas.toArray(new String[datas.size()]));
        } else {
            content = String.format(BehaviorTrackFormatConst.UntalkFormFormat2, datas.toArray(new String[datas.size()]));
        }
        return content;
    }

}